//
//  FileVC.swift
//  YueChat
//
//  Created by 1 on 2024/10/5.
//

import UIKit
import WebKit
import Alamofire
//import Alamofire

class FileVC: BaseVC,UIDocumentInteractionControllerDelegate {

        var webView: WKWebView?
        var url: String?
        var fileName: String?
//        var isHideNav: Bool = false
        var doVC: UIDocumentInteractionController?
//        var sessionManager: AFHTTPSessionManager?
//        var addBtn: UIButton?

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
//            navigationController?.setNavigationBarHidden(isHideNav, animated: animated)
        }

        lazy var addBtn: UIButton = {
            let button = UIButton(frame: CGRect(x: 50, y: 0, width: 44, height: 44))
            button.setTitle(KLocalizedString("SettingSave"), for: .normal)
            button.setTitleColor(UIColor.black, for: .normal)
            button.addTarget(self, action: #selector(previewFileWithURL), for: .touchUpInside)
            return button
        }()

//        var sessionManager: URLSession {
//            didSet {
////                sessionManager?.requestSerializer.timeoutInterval = 45.0
//////                sessionManager?.responseSerializer = JSONResponseSerializer()
////                sessionManager?.responseSerializer.acceptableContentTypes = [
////                    "application/json",
////                    "text/html",
////                    "text/json",
////                    "text/plain",
////                    "text/javascript",
////                    "text/xml",
////                    "image/*"
////                ]
//                let config = URLSessionConfiguration.default
//                sessionManager = URLSession(configuration: config, delegate: nil, delegateQueue: OperationQueue.main)
//            }
//        }

        @objc func previewFileWithURL() {
            let url = URL(string: self.url ?? "")
            MHAlert.showLoadingStr(KLocalizedString("loadLoad"))
            if url!.isFileURL, let filePath = url?.path, FileManager.default.fileExists(atPath: filePath) {
                doVC = UIDocumentInteractionController(url: url!)
                doVC?.delegate = self
                doVC?.presentOpenInMenu(from: view.bounds, in: view, animated: true)
            } else if url?.scheme?.contains("http") == true {
                
                let documentDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
                let filePathURL = documentDirectory.appendingPathComponent(url!.lastPathComponent)
                let filePathString = filePathURL.path
                let request = URLRequest(url: url!)
                
                

                let session = URLSession.shared
                let downloadTask = session.downloadTask(with: request,
                       completionHandler: { (location:URL?, response:URLResponse?, error:Error?)
                        -> Void in
//                        print("location:\(location)")
//                        let locationPath = location!.path
//                        let documnets:String = NSHomeDirectory() + "/Documents/1.png"
//                        let fileManager = FileManager.default
//                        try! fileManager.moveItem(atPath: locationPath, toPath: documnets)
//                        print("new location:\(documnets)")
                    
                    self.doVC = UIDocumentInteractionController(url: location!)
                    self.doVC?.delegate = self
                    GK_main_async_safe {
                        self.doVC?.presentOpenInMenu(from: self.view.bounds, in: self.view, animated: true)
                    }
                    })
                downloadTask.resume()
                
//                let downloadTask = sessionManager.downloadTask(with: request) { <#URL?#>, <#URLResponse?#>, <#(any Error)?#> in
//                    <#code#>
//                }//.downloadTask(with: request, progress: { pro in
//                    
//                }, destination: { path, response in
//                    return URL(fileURLWithPath: filePathString)
//                }, completionHandler: { response, filePath, error in
////                    defer { MHAlert.hideLoading() }
//                    self.doVC = UIDocumentInteractionController(url: filePath!)
//                    self.doVC?.delegate = self
//                    self.doVC?.presentOpenInMenu(from: self.view.bounds, in: self.view, animated: true)
//                })
//                downloadTask?.resume()
            }
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

    init(withUrl url: String,fileName:String) {
            self.url = url
        self.fileName = fileName
            super.init(nibName: nil, bundle: nil)
        }

        override func viewDidLoad() {
            super.viewDidLoad()

            self.title = self.fileName
//            navigationItem.rightBarButtonItem = UIBarButtonItem(customView: addBtn)
            webView = WKWebView(frame: CGRect(x: 0, y: 20 + 44, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 44))
            view.addSubview(webView!)
            
            
            let str = getHomeFilePath(localPath: url!)
//            let res2 = FileManager.default.fileExists(atPath: str)
//            loadTxt(pageURL: URL(fileURLWithPath: str))
//            let originalString = "123.txt"
//
//            let newURL = URL(fileURLWithPath: str).deletingLastPathComponent().appendingPathComponent(originalString)
////                    var file2 = "\(file)/nihao"
//            do {
//                try FileManager.default.moveItem(at: URL(fileURLWithPath: str), to: newURL)
//                print("文件名更改成功！")
//            } catch {
//                print("文件名更改失败：\(error)")
//            }
//            var file = newURL.absoluteString
//            if file.hasPrefix("file://") {
//                file = file.replacingOccurrences(of: "file://", with: "")
            
            if fileName!.contains(".txt") {
                let pageURL = URL(fileURLWithPath: str)
                if var body = try? String(contentsOf: pageURL, encoding: .utf8) {
                    body = body.replacingOccurrences(of: "\n", with: "<br/>", options: [], range: nil)
                    webView?.loadHTMLString(body, baseURL: nil)
                } else if var body = try? String(contentsOf: pageURL, encoding: String.Encoding(rawValue: 0x80000632)) {
                    body = body.replacingOccurrences(of: "\n", with: "<br/>", options: [], range: nil)
                    webView?.loadHTMLString(body, baseURL: nil)
                } else if var body = try? String(contentsOf: pageURL, encoding: String.Encoding(rawValue: 0x80000631)) {
                    body = body.replacingOccurrences(of: "\n", with: "<br/>", options: [], range: nil)
                    webView?.loadHTMLString(body, baseURL: nil)
                } else {
                    webView?.load(URLRequest(url: pageURL))
                }
            }else{
                webView?.load(URLRequest(url: URL(fileURLWithPath: str)))
            }
            
        }

        func loadTxt(pageURL: URL) {
            let lastName = pageURL.lastPathComponent.lowercased()
            if lastName.contains(".txt") {
                if var body = try? String(contentsOf: pageURL, encoding: .utf8) {
                    body = body.replacingOccurrences(of: "\n", with: "<br/>", options: [], range: nil)
                    webView?.loadHTMLString(body, baseURL: nil)
                } else if var body = try? String(contentsOf: pageURL, encoding: String.Encoding(rawValue: 0x80000632)) {
                    body = body.replacingOccurrences(of: "\n", with: "<br/>", options: [], range: nil)
                    webView?.loadHTMLString(body, baseURL: nil)
                } else if var body = try? String(contentsOf: pageURL, encoding: String.Encoding(rawValue: 0x80000631)) {
                    body = body.replacingOccurrences(of: "\n", with: "<br/>", options: [], range: nil)
                    webView?.loadHTMLString(body, baseURL: nil)
                } else {
                    webView?.load(URLRequest(url: pageURL))
                }
            } else {
                webView?.load(URLRequest(url: pageURL))
            }
        }

        deinit {
            print("==ZoloWalletViewController===dealloc==")
        }
    }
